<?php
/**
* 微信公众平台账号信息
*/
class mc_weixin_account {

	protected $role_boj;

	private static $instant = null;

	public static function instant($role_boj)
	{
		if(!self::$instant)  {
			self::$instant = new self($role_boj);
		}
		return self::$instant;
	}

	protected function __construct($role_boj)
	{
		$this->site = $role_boj;
	}

	//获取高级接口需要的access_token信息  $force表示强制从服务器获取access_token
	public function getAccessToken($force = false) 
	{
		$config_obj = _G('loader')->model('config');
		$data = $config_obj->read('access_token', 'weixin');
		if($data) list($access_token, $expires_time) = explode("\t",$data['value']);
		//判断是否失效
		if($force || ! $this->role_obj->access_token || ($this->role_obj->expires_in > 0 && $this->role_obj->expires_in < _G('timestamp'))) {
			$this->_getAccessToken();
		} elseif($this->role_obj->access_token) {
			$this->access_token = $access_token;
		}
	}

	//从微信服务器获取access_token
	private function _getAccessToken()
	{
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
		$data = http_get($url);
		if($data) $json = json_decode($data, true);
		if($json['access_token']) {
			$this->access_token = $json['access_token'];
			//保存到数据库
			$this->role_obj->save_access_token($json['access_token'], (_G('timestamp') + $json['expires_in'] - 100));

		} else {
			log_write('weixin', $url."\n".$data);
		}
	}

}